var Fly=require("flyio") //wx.js为您下载的源码文件
import {FlyRequestConfig,FlyPromise,FlyErrResponse,FlyError, FlyResponse} from "flyio"
import getHttpStatusMessage from './request/getHttpStatusMessage';
import url from '../config/url'
import { showToast } from "./showToast";
var fly = new Fly(); //创建fly实例
//配置请求基地址
fly.config.baseURL = url.httpUrl
//添加拦截器
fly.interceptors.request.use(async(config:FlyRequestConfig) => {
  wx.showLoading({
    title: '加载中',
    mask: true
  })
  //给所有请求添加自定义header
  config.headers["content-type"] = "application/json"
  let accountInfo = wx.getAccountInfoSync();
  let appid = accountInfo.miniProgram.appId;
  let envVersion=accountInfo.miniProgram.envVersion
  config.headers["appid"] = appid
  config.headers["envversion"] =  envVersion
  if (wx.getStorageSync('token')) {
    config.headers["Authorization"] = wx.getStorageSync('token')
  }
  return config;
})



fly.interceptors.response.use((response:FlyErrResponse,  promise:FlyPromise) => {
  wx.hideLoading()
  if(response.data.code!=1000){
    promise.reject(response.data)
  }else{
    promise.resolve(response.data.data)
  }
}, (err:FlyError, promise:FlyPromise<FlyErrResponse>) => {
  wx.hideLoading()
  if(err.response){
    console.log("data",err.response?.data);
    showToast(err.response?.data.message)
    promise.reject(err.response?.data)
  }else{
    const message = getHttpStatusMessage(err.status);
    showToast(message)
    promise.reject(err.response?.data)
  }

})


export default fly